import { connect } from '@/dva';
import Content from './content';
import { ConnectProps } from '@/dva/types';
import { CloneProps } from '@/components/ModalPro';
import React, { useEffect, useCallback, useRef } from 'react';
import { State as ImageSourceState } from '@/models/imageSource/types';
import { ListItem as ClassifyItem } from '@/service/image/getClassifyList';

type Props = ConnectProps & CloneProps & {
  onSuccess: Function;
  classifyItem: ClassifyItem;
  imageSource: ImageSourceState;
}

const Index = (props: Props) => {
  const {
    imageSource,
    classifyItem
  } = props;

  const {
    submitLoading = false
  } = imageSource || {};

  const instance = useRef<any>();

  const classify = classifyItem?._id;

  const onSubmit = useCallback(async () => {
    const type:string = 'imageSource/createNew';
    const fields = await instance.current?.onSubmit();
    const payload = { ...fields, classify };
    await props?.commit?.(type, payload);
    props?.onSuccess?.();
    props?.closeModal?.();
  }, [classify]);

  useEffect(() => {
    props?.listenOk?.(onSubmit);
  }, []);

  useEffect(() => {
    if (!submitLoading) {
      props?.submitStop?.();
    } else {
      props?.submitLoading?.();
    }
  }, [submitLoading]);

  return (
    <Content
      ref={instance}
      classifyItem={classifyItem}
    />
  )
}

export default connect({
  imageSource: ({ imageSource }) => imageSource
})(Index);
